package shajie.shajun.mmhf.Control;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;

import com.nineoldandroids.view.ViewHelper;

import shajie.shajun.mmhf.Interface.CeHuaScrollInterface;
import shajie.shajun.mmhf.Public_Data;
import shajie.shajun.mmhf.R;

/**
 * Created by Administrator on 2017/11/3.
 */

public class CeHuaScrollView extends HorizontalScrollView{
    private LinearLayout mWapper;
    private ViewGroup mMenu;
    private ViewGroup mContent;
    private int mScreenWidth;
    private int mMenuWidth;
    // dp
    private int mMenuRightPadding = 140;
    private String TAG="CeHuaScrollView";
    private boolean once;

    private boolean isOpen=false;
    private CeHuaScrollInterface ceHuaScrollInterface;
    private int mLastXIntercept;
    private int mLastYIntercept;
    private int touchSlop;

    @Override
    public void fling(int velocityx) {
        super.fling(1000);//这里设置滑动的速度
    }
    public CeHuaScrollView(Context context, AttributeSet attrs)
    {
        this(context, attrs, 0);
    }

    public CeHuaScrollView(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);

        TypedArray a = context.getTheme().obtainStyledAttributes(attrs,
                R.styleable.SlidingMenu, defStyle, 0);

        int n = a.getIndexCount();
        for (int i = 0; i < n; i++)
        {
            int attr = a.getIndex(i);
            switch (attr)
            {
                case R.styleable.SlidingMenu_rightPadding:
                    mMenuRightPadding = a.getDimensionPixelSize(attr,
                            (int) TypedValue.applyDimension(
                                    TypedValue.COMPLEX_UNIT_DIP, 50, context
                                            .getResources().getDisplayMetrics()));
                    break;
            }
        }
        a.recycle();

        WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        mScreenWidth = outMetrics.widthPixels;

        touchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop();
    }

    public CeHuaScrollView(Context context)
    {
        this(context, null);
    }
/*    private void smoothScrollto(int destx,int duration){
        int lasts=getScrollX();
        int deltax=destx-lasts;
        scroller.startScroll(lasts,0,deltax,0,duration);
        invalidate();
    }

    @Override
    public void computeScroll() {
        super.computeScroll();
        if (scroller.computeScrollOffset()){
            scrollTo(scroller.getCurrX(),scroller.getCurrY());
            postInvalidate();
        }
    }*/

    public void addopenmenuListener(CeHuaScrollInterface ceHuaScrollInterface){
        this.ceHuaScrollInterface=ceHuaScrollInterface;
    }
    /**
     * 设置子View的宽和高 设置自己的宽和高
     */
    private int mWidth,mHeight;
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
        if (!once)
        {
            mWapper = (LinearLayout) getChildAt(0);
            mMenu = (ViewGroup) mWapper.getChildAt(0);
            mContent = (ViewGroup) mWapper.getChildAt(1);
            mMenuWidth = mMenu.getLayoutParams().width = mScreenWidth
                    - mMenuRightPadding;
            mContent.getLayoutParams().width = mScreenWidth;
            once = true;
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        mWidth = getMeasuredWidth();
        mHeight = getMeasuredHeight();
    }
    /**
     * 通过设置偏移量，将menu隐藏
     */

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b)
    {
        super.onLayout(changed, l, t, r, b);
        if (changed)
        {
            this.scrollTo(mMenuWidth, 0);
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        return super.dispatchTouchEvent(ev);
    }

    private boolean dou=true,move=false;
    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        //这个是侧滑菜单的拦截


        //1.侧滑菜单下面是一个viewpager，我想实现的是在第0野可以侧滑菜单，不然就是viewpager滑动
        //2.在第0页向左侧滑也能滑动viewpager

        //在第0页既能侧滑，也能滑动，对，右滑是侧滑菜单，左滑是viewpager
        int x = (int) ev.getX();
        int y = (int) ev.getY();
        switch (ev.getAction()){
            case MotionEvent.ACTION_DOWN:
                mLastXIntercept = x;
                mLastYIntercept = y;
                dou=true;
                move=false;
                break;
            case MotionEvent.ACTION_MOVE:
                int deltaX = x - mLastXIntercept;
                int deltaY=y-mLastYIntercept;
                int absx=Math.abs(x-mLastXIntercept);
                int absy=Math.abs(y-mLastYIntercept);

                if (dou) {
                    if (absx< 4 && absy < 4) {
                        dou=true;
                        break;
                    }else {
                        dou=false;
                    }
                }
                if (absx > absy||move) {
                    move=true;
                    if (deltaX > 0) {
                        if (Public_Data.pagerselect == 0) {
                            return true;
                        } else {
                            return false;
                        }
                    } else if (!isOpen) {
                        return false;
                    } else {
                        return true;
                    }
                } else {
                    return false;
                }
            case MotionEvent.ACTION_UP:
                dou=true;
                mLastXIntercept = mLastYIntercept = 0;
            case MotionEvent.ACTION_CANCEL:
                break;
        }

        return super.onInterceptTouchEvent(ev);
    }


    /**
     * 画阴影部分*//*
    @Override
    protected void dispatchDraw(Canvas canvas) {
        super.dispatchDraw(canvas);
        RectF rectF = new RectF(0, (mHeight-mHeight*rightScale)/2, mMenuWidth,mHeight*rightScale/2+mHeight/2);
        Paint paint = new Paint();

        paint.setAntiAlias(true);
        LinearGradient linearGradient = new LinearGradient(mMenuWidth-30*rightScale, 0,
                mMenuWidth, 0, 0x00555555, 0x3f333333, Shader.TileMode.CLAMP);
        paint.setShader(linearGradient);
        paint.setStyle(Paint.Style.FILL);
        canvas.drawRect(rectF, paint);
        ViewHelper.setPivotX(mContent, 0);
        ViewHelper.setPivotY(mContent, mContent.getHeight() / 2);

    }*/
    //原生的viewpager左右滑动可以用了吗，有没有解除设置警用
    //解除了，之前不是演示的么，可以用的
    //再说了，原生的也没法设置禁用的
    @Override
    public boolean onTouchEvent(MotionEvent ev) {

       // Log.e(TAG, "onTouchEvent: 执行________");

        int action = ev.getAction();
        switch (action)
        {
            //这个主作用就是再判断up的时候，判断是否自动打开菜单，也就是说他不处理滑动事件的
            case MotionEvent.ACTION_UP:
                // 隐藏在左边的宽度
                float scrollX = getScrollX();//mMenuWidth~0  初始值：mMenuWidth
                if (isOpen==true) {
                    if (scrollX >= mMenuWidth / 8) {
                        this.smoothScrollTo(mMenuWidth, 0);//显示内容
                        isOpen = false;
                        ceHuaScrollInterface.openmenuListener(false);
                    }else{
                        this.smoothScrollTo(0, 0);//显示菜单
                        isOpen =true;
                        ceHuaScrollInterface.openmenuListener(true);
                    }
                }else
                {
                    if (scrollX<mMenuWidth /1.1) {
                        this.smoothScrollTo(0, 0);   //显示菜单
                        isOpen = true;
                        ceHuaScrollInterface.openmenuListener(true);
                    }else{
                        this.smoothScrollTo(mMenuWidth, 0);   //显示内容
                        isOpen = false;
                        ceHuaScrollInterface.openmenuListener(false);
                    }
                }
                return true;
        }
        //这一块执行了吗，执行了，你跟着我指的看
        return super.onTouchEvent(ev);
    }

    /**
     * 打开菜单
     */
    public void openMenu()
    {
        if (isOpen)
            return;
        ceHuaScrollInterface.openmenuListener(true);
        this.smoothScrollTo(0, 0);
        isOpen = true;
    }

    public void closeMenu()
    {
        if (!isOpen)
            return;
        ceHuaScrollInterface.openmenuListener(false);
        this.smoothScrollTo(mMenuWidth, 0);
        isOpen = false;
    }

    /**
     * 切换菜单
     */
    public void toggle()
    {
        if (isOpen)
        {
            closeMenu();
        } else
        {
            openMenu();
        }
    }

    /**
     * 滚动发生时
     */
    private float leftmenu;
    private float rightScale; //0.7~1
    private float scale;
    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt)
    {
        super.onScrollChanged(l, t, oldl, oldt);
         scale = l * 1.0f / mMenuWidth; // 1 ~ 0
        /**
         * 区别1：内容区域1.0~0.7 缩放的效果 scale : 1.0~0.0 0.7 + 0.3 * scale
         *
         * 区别2：菜单的偏移量需要修改
         *
         * 区别3：菜单的显示时有缩放以及透明度变化 缩放：0.7 ~1.0 1.0 - scale * 0.3 透明度 0.6 ~ 1.0
         * 0.6+ 0.4 * (1- scale) ;
         *
         */
        rightScale = 0.8f + 0.2f * scale; //0.7~1
        float leftScale = 1.0f - scale * 0.2f;    //1~0.7
        float leftAlpha = 1f * (1 - scale);//透明度变化 0.4~1
        float rightAlpha = 1f - 0.7f * (1 - scale);//透明度变化 0.4~1
        // 调用属性动画，设置TranslationX
        ViewHelper.setTranslationX(mMenu, mMenuWidth *scale* 0.75f);//部分隐藏在左侧


        ViewHelper.setScaleX(mMenu, leftScale);
        ViewHelper.setScaleY(mMenu, leftScale);
        ViewHelper.setAlpha(mMenu, leftAlpha);
        // 设置content的缩放的中心点
        ViewHelper.setPivotX(mContent, 0);
        ViewHelper.setPivotY(mContent, mContent.getHeight() / 2);
        ViewHelper.setAlpha(mContent, rightAlpha);
        ViewHelper.setScaleX(mContent, rightScale);
        ViewHelper.setScaleY(mContent, rightScale);


    }

}